package com.movie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movie.bean.*;
import com.movie.bean.vo.UserQueryVO;
import com.movie.common.HttpResult;
import com.movie.enums.OrderStatus;
import com.movie.service.MovieService;
import com.movie.service.UserService;
import com.movie.utils.PageUtil;
import com.movie.utils.TicketOrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.movie.enums.OrderStatus.PAID;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MovieService movieService;
    @Autowired
    private TicketOrderUtil ticketOrderUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/HandleUserRegister")
    @ResponseBody
    public void HandleUserRegister(@RequestBody User user) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String time = df.format(date);
        user.setUregisterTime(time);
        userService.HandleUserRegister(user);
    }

    @PostMapping("/userPage")
    public HttpResult<Page<User>> userPage(@RequestBody UserQueryVO userQueryVO){
        return HttpResult.success(userService.userPage(userQueryVO));
    }

    @PostMapping("/updateInfo")
    public HttpResult<User> updateInfo(@RequestBody User user){
        User res = userService.updateInfo(user);
        return HttpResult.success(res);
    }

    @PostMapping("/banUser")
    public HttpResult<String> banUser(@RequestBody User user){
        userService.banUser(user);
        return HttpResult.success();
    }


    @GetMapping("/CheckName")
    @ResponseBody
    public boolean CheckName(String username) {
        int row = userService.CheckName(username);
        return row == 0 ? true : false;
    }

    @GetMapping("/UserLogin")
    @ResponseBody
    public Map<String, Object> userLogin(String uname, String upassword, String inputCode, HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        User user = userService.CheckLogin(uname, upassword);
        map.put("user", user);
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("checkcode");
        if (user == null) {
            map.put("is", false);
            map.put("message", "用户名或密码错误!");
        } else if (user != null && !code.equals(inputCode)) {
            map.put("is", false);
            map.put("message", "验证码有误!");
        } else if (user != null && code.equals(inputCode)) {
            if (user.getUstatus() == 0) {
                map.put("is", true);
                map.put("message", "登入成功!");
                map.put("user", user);
            } else {
                map.put("is", false);
                map.put("message", "该帐号状态异常,请联系管理员!");
            }

        }
        return map;
    }

    @GetMapping("/GetUserPaidTicketList")
    @ResponseBody
    public List<TicketOrder> getUserPaidTicketList(int uid) {
        return userService.getUserPaidTicketList(uid);
    }

    @PostMapping("/UpdateBalance")
    @ResponseBody
    public User updateBalance(int money, int uid) {
        userService.updateBalance(money, uid);
        return userService.getUserByUid(uid);
    }




    @GetMapping("/UpDateUserInfo")
    @ResponseBody
    public User upDateUserInfo(int uid) {
        return userService.getUserByUid(uid);
    }


    @GetMapping("/getTicketOrder")
    @ResponseBody
    public Page<TicketOrder> geTWaitPaidUserOrderList(Integer uid, Integer status, Integer pageNo, Integer pageSize) {
        List<TicketOrder> orderList = new ArrayList<>();
        OrderStatus orderEnum = OrderStatus.getOrderEnum(status);
        switch (orderEnum) {
            case UNPAID:
                LinkedHashSet<String> keys = (LinkedHashSet<String>) redisTemplate.keys("order:" + uid + ":number:*");
                if (keys != null) {
                    for (String key : keys) {
                        long expireTime = redisTemplate.getExpire(key);
                        List<Ticket> ticketList = (List<Ticket>) redisTemplate.opsForValue().get(key);
                        orderList.add(ticketOrderUtil.ticketOrderUtil(ticketList, expireTime));
                    }
                }
                break;
            case PAID:
            case REFUND:
                List<TicketOrder> ticketOrderByStatus = movieService.getTicketOrderByStatus(uid, status, pageNo, pageSize);
                orderList.addAll(ticketOrderByStatus);
                break;
        }
        return PageUtil.PaginatedResult(orderList, pageNo, pageSize);
    }

    @PostMapping("UpdateTicketStatus")
    @ResponseBody
    public Map<String, Object> updateTicketStatus(String number, int total, int uid) {
        Map<String, Object> map = new HashMap<>();
        try {
            LinkedHashSet<String> key = (LinkedHashSet<String>) redisTemplate.keys("*:" + number);
            List<Ticket> ticketList = new ArrayList<>();
            for (String k : key) ticketList = (List<Ticket>) redisTemplate.opsForValue().get(k);
            for (Ticket ticket : ticketList) {
                ticket.setStatus(1);//插入支付订单数据库表同时status设置为1，已支付
                ticket.setDelFlag(0);
            }
            userService.updateTicketStatus(number, total, uid, ticketList);
            redisTemplate.delete(key);//缓存中删除订单
            key = (LinkedHashSet<String>) redisTemplate.keys("*:" + number + ":*");//删除该场次的对应订单的座位号
            redisTemplate.delete(key);
//            userService.updateTicketStatus(number, total, uid);
            map.put("isSuccess", true);
            return map;
        } catch (Exception e) {
            System.out.println(e);
            map.put("isSuccess", false);
            map.put("result", "你的余额不足!");
            return map;
        }
    }

//    @PostMapping("/Test")  测试文件+普通数据上传，对应前端代码在tabs_page C2组件中
//    @ResponseBody
//    public void test(@RequestParam("img") MultipartFile img,HttpSession session,User user) throws IOException {
//        String fileName = img.getOriginalFilename();
//        System.out.println(fileName);
//        System.out.println(user);
//        //处理文件重名问题
//        String hzName = fileName.substring(fileName.lastIndexOf("."));
//        fileName = UUID.randomUUID().toString() + hzName;
//        //获取服务器中photo目录的路径
//        ServletContext servletContext = session.getServletContext();
//        String photoPath = servletContext.getRealPath("test");
//        File file = new File(photoPath);
//        if (!file.exists()) {
//            file.mkdir();
//        }
//        String finalPath = photoPath + File.separator + fileName;
//        //实现上传功能,其实即文件转移到对应文件夹下
//        img.transferTo(new File(finalPath));
//    }


    @PostMapping("/HandleDeleteUserOrder")
    @ResponseBody
    public void handleDeleteUserOrder(String number,Integer status) {
        userService.handleDeleteUserOrder(number,status);
    }

//    @GetMapping("/HandleUpdateUserOrderList")
//    @ResponseBody
//    public List<TicketOrder> HandleUpdateUserOrderList(int uid) {
//        return userService.geTWaitPaidUserOrderList(uid);
//    }


    @PostMapping("/AddComment")
    @ResponseBody
    public HttpResult<String> addComment(Comment comment) {
        System.out.println(comment);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        comment.setTime(dateFormat.format(new Date()));
        int count = userService.checkedComment(comment.getMid(), comment.getUid());
        if (count>0) {
            userService.addComment(comment);
            return HttpResult.success();
        } else return HttpResult.error("抱歉，请观影后才能评论哦!");
    }

    @GetMapping("/GetCommentList")
    @ResponseBody
    public List<Comment> getCommentList(int uid, int mid) {
        List<Comment> comments = userService.getCommentList(mid);
        for (int i = 0; i < comments.size(); i++) {
            int cId = comments.get(i).getCid();
            CommentLike commentLike = userService.isExistCommentLike(uid, cId);
            if (commentLike == null)
                comments.get(i).setLike(false);
            else
                comments.get(i).setLike(true);
        }
        return comments;
    }

    @PostMapping("/DelLike")
    @ResponseBody
    public List<Comment> delLike(int uid, int cid, int mid) {
        userService.delLike(uid, cid);
        List<Comment> comments = userService.getCommentList(mid);
        for (int i = 0; i < comments.size(); i++) {
            int cId = comments.get(i).getCid();
            CommentLike commentLike = userService.isExistCommentLike(uid, cId);
            if (commentLike == null)
                comments.get(i).setLike(false);
            else
                comments.get(i).setLike(true);
        }
        return comments;
    }

    @PostMapping("/AddLike")
    @ResponseBody
    public List<Comment> addLike(int uid, int cid, int mid) {
        userService.addLike(uid, cid);
        List<Comment> comments = userService.getCommentList(mid);
        for (int i = 0; i < comments.size(); i++) {
            int cId = comments.get(i).getCid();
            CommentLike commentLike = userService.isExistCommentLike(uid, cId);
            if (commentLike == null)
                comments.get(i).setLike(false);
            else
                comments.get(i).setLike(true);
        }
        return comments;
    }

    @PostMapping("/AddFavorite")
    @ResponseBody
    public Map<String, Object> addFavorite(Favorite favorite, String type) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (type.equals("add")) {
                userService.addFavorite(favorite);
                map.put("message", "已添加收藏!");
                map.put("isFavorite", true);
            } else {
                userService.delFavorite(favorite);
                map.put("message", "已取消收藏!");
                map.put("isFavorite", false);
            }
            map.put("isError", false);
        } catch (Exception e) {
            map.put("message", "操作失败!");
            map.put("isError", true);
        } finally {
            return map;
        }
    }

    @GetMapping("/IsExistFavorite")
    @ResponseBody
    public boolean isExistFavorite(int uid, int mid) {
        return userService.isExistFavorite(uid, mid) == null ? false : true;
    }



//    @Autowired
//    private RedisTemplate<String,Object> redisTemplate;
//    @GetMapping("/test")
//    @ResponseBody
//    public ArrayList<Ticket> test(){
//        LinkedHashSet<String> keys = (LinkedHashSet<String>) redisTemplate.keys("order:7:number:*");
//        ArrayList<ArrayList<Ticket>> tickets = new ArrayList<>();
//        if (keys!=null) for (String key:keys) tickets.add((ArrayList<Ticket>) redisTemplate.opsForValue().get(key));;
//        return tickets;
//    }
}
